package com.example.waibao.controller;

import com.example.waibao.Component.UserHelper;
import com.example.waibao.entity.*;
import com.example.waibao.service.impl.SseEmitterServer;
import com.example.waibao.service.materialService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.example.waibao.utils.material_Util;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@RestController
public class materialController {

    @Autowired
    private materialService materialService;


    @Autowired
    private UserHelper userHelper;

//    @RequestParam("file")MultipartFile file,
//    @RequestParam("building_name")String building_name,
//    @RequestParam("school_id")int school_id
    //这里是单个上传，也可以做批量上传
    @PostMapping("/save_building")
    public ResponseResult save_building(@RequestBody  MultipartFile file) throws IOException {

   //     User user = userHelper.getCurrentUser();

       // String url = material_Util.uploadImage(building.getFile(), building.getBuilding_name());
       // building.getFile()
        String url = material_Util.uploadImage(file);

//        materialService.save_building(building.getBuilding_name(),url,building.getSchool_id());
     //   materialService.save_building(building.getBuilding_name(),url,user.getSchool_id());

        ResponseResult result = new ResponseResult(200, "上传成功", url);
        return result;
    }
    //这里是单独按照图片名来获取，也可以批量一次性获取所有图片
    @GetMapping("/get_building")
    public ResponseResult get_building(building  building,
                                       @RequestParam(name = "page_num", defaultValue = "1")Integer page_num,
                                       @RequestParam(name = "page_size", defaultValue = "5")Integer page_size){
//        @RequestParam("school_id")int school_id,
//        @RequestParam("building_name")String building_name
    //    System.out.println(building.getBuilding_name());

        User user = userHelper.getCurrentUser();

//        List<building> img_urls = materialService.get_building(building.getBuilding_name(), building.getSchool_id());

        PageInfo<building> img_urls = materialService.get_building(building.getBuilding_name(), user.getSchool_id(),page_num, page_size);
        ResponseResult result = new ResponseResult(200, "获取建筑物图片成功", img_urls);
        return result;
    }


    //这里是查找所有的图片地址
    @GetMapping("/getAllImg")
    public ResponseResult getAllImg(){

        List<building> img_urls = materialService.getAllImg();

        ResponseResult result = new ResponseResult(200, "获取成功", img_urls);
        return result;

    }






   // @RequestBody JSONObject map
    @GetMapping("save_map2")
    @PreAuthorize("hasAuthority('system:dept:save_map')")
    private ResponseResult save_map(@RequestParam("modal") String map,
                                    @RequestParam("modal") String modal,
                                    @RequestParam("scope") String scope,
                                    @RequestParam("legend") String legend,
                                    @RequestParam("school") int school_id) throws JsonProcessingException {

        System.out.println(map);
        ObjectMapper mapper = new ObjectMapper();
        Map<String,Object> maps = mapper.readValue(map, Map.class);
        //一种就是直接从前端接收来的字符串存入数据库中

        //一种就是分字段的存，用for循环存入数据库

        materialService.save_map(map,modal,scope,legend,school_id);
        //可以放到redis中

        ResponseResult result = new ResponseResult(200, "保存成功");
        return result;
    }

    @PostMapping("save_map")
   // @PreAuthorize("hasAuthority('system:dept:save_map')")
        public ResponseResult save_map2(@RequestBody Map<String,Object> school_map) throws JsonProcessingException {

//        Map<String,Object> school_map = all_map.getSchool_map();
//        String url = material_Util.uploadImage(all_map.getFile(), building.getBuilding_name());



        //修改的话多个查询和删除操作，先查询出来是否已有该学校的地图如果已存在则先删除再插入。
        User user = userHelper.getCurrentUser();
//        int school_id =Integer.parseInt(school_map.get("school_id").toString());
        int school_id =user.getSchool_id();
        school_map s =   materialService.get_school_map(school_id);
        List<school_map_legend> school_map_legend = materialService.get_school_map_legend(school_id);
        if(s!=null){
            materialService.delete_school_map(s.getSchool_id());
        }
        if(!school_map_legend.isEmpty()){
            materialService.delete_school_map_legend(school_id);
        }
        System.out.println(school_map);

//        ObjectMapper mapper = new ObjectMapper();
//        Map<String,Object> maps = mapper.readValue(map, Map.class);
//        //一种就是直接从前端接收来的字符串存入数据库中
//
//        //一种就是分字段的存，用for循环存入数据库
//
//        materialService.save_map(map,modal,scope,legend,school_id);

        //可以放到redis中

        String map = null;
        if(school_map.get("map")!=null){
             map = school_map.get("map").toString();
        }
        String area = null;
        if(school_map.get("area")!=null){
            area = school_map.get("area").toString();
        }

      materialService.save_school_map(school_map.get("model"),map,
               school_id,area);

//        scope door

        System.out.println("scope=  "+school_map.get("scope"));
      //前端传来的id
        List<String> scope = null;
        List<String> door = null;
        List<Integer> id = (List<Integer>) school_map.get("id");
        List<String> name = (List<String>) school_map.get("name");

        if(school_map.get("scope")!=null&&school_map.get("scope")!=""){
            scope = (List<String>) school_map.get("scope");
        }
        List<String> image = (List<String>) school_map.get("image");
        List<String> introduce_image = (List<String>) school_map.get("introduce_image");
        List<String> introduce = (List<String>) school_map.get("introduce");
        List<String> color = (List<String>) school_map.get("color");
        if(school_map.get("door")!=null&&school_map.get("door")!=""){
            door = (List<String>) school_map.get("door");
        }

        System.out.println(map);
        System.out.println(name);
        System.out.println(scope);

        for(int i=0;i<name.size();i++){
            if(scope!=null&&door!=null){
                materialService.save_school_map_legend(id.get(i),name.get(i),scope.get(i),
                        image.get(i),color.get(i),door.get(i),school_id,introduce_image.get(i),introduce.get(i));
            }else if(scope!=null){
                materialService.save_school_map_legend(id.get(i),name.get(i),scope.get(i),
                        image.get(i),color.get(i),null,school_id,introduce_image.get(i),introduce.get(i));
            }else if(door!=null){
                materialService.save_school_map_legend(id.get(i),name.get(i),null,
                        image.get(i),color.get(i),door.get(i),school_id,introduce_image.get(i),introduce.get(i));
            }else {
                materialService.save_school_map_legend(id.get(i),name.get(i),null,
                        image.get(i),color.get(i),null,school_id,introduce_image.get(i),introduce.get(i));
            }
        }
        //materialService.save_school_map_legend(school_map.get("legend"));
        ResponseResult result = new ResponseResult(200, "地图信息保存成功");
        return result;
    }

    //获取地图
    @GetMapping("get_map")
    public ResponseResult get_map(){

        User user = userHelper.getCurrentUser();
        int school_id = user.getSchool_id();
        school_map school_map = materialService.get_school_map(school_id);
        List<school_map_legend> school_map_legend = materialService.get_school_map_legend(school_id);
        System.out.println(school_map_legend);

        the_school_map the_school_map = new the_school_map();
//        if(school_map.getMap()!=null){
//            the_school_map.setMap(school_map.getMap());
//        }
//        if(school_map.getScope()!=null){
//            the_school_map.setScope(school_map.getScope());
//        }

        if(school_map!=null){
            the_school_map.setMap(school_map.getMap());
            the_school_map.setSchool_id(school_map.getSchool_id());
            the_school_map.setId(school_map.getId());
            the_school_map.setScope(school_map.getScope());
            the_school_map.setModel(school_map.getModel());

        }

        if(school_map_legend!=null){
            the_school_map.setLegend(school_map_legend);
        }
        ResponseResult result = new ResponseResult(200, "地图获取成功", the_school_map);
        return result;


    }

//    @PostMapping("save_school_map_legend")
//    private ResponseResult save_school_map_legend(@RequestBody List<school_map_legend> school_map_legend){
//       // @RequestBody List<school_map_legend> school_map_legend
//
//        //materialService.save_school_map_legend(school_map_legend);
////        for (school_map_legend s: school_map_legend) {
////           // materialService.save_school_map_legend(s);
////        }
//
//    //    List<String> name = (List<String>) school_map.get("name");
//        ResponseResult result = new ResponseResult(200, "保存school_map_legend成功");
//        return result;
//    }

    //任务的设置,加载地图时，可以从redis缓存读取这样更快
    @PostMapping("Assign_tasks")
    public ResponseResult Assign_tasks(@RequestBody to_task toTask){
//        @RequestParam("task_id")List<Integer> task_id,
//        @RequestParam("place") String place,
//        @RequestParam("school_id") int school_id
        User user = userHelper.getCurrentUser();
        int school_id = user.getSchool_id();
        for (int id : toTask.getTask_id()) {
            materialService.add_task_place(id, toTask.getThe_place(),school_id);
        }
        //存入to_task数据表中一对多
        ResponseResult result = new ResponseResult(200, "任务分配成功");
        return  result;
    }


    //设置各个地点任务版本2
    @PostMapping("Assign_tasks2")
    public ResponseResult Assign_tasks2(@RequestBody to_task2 toTask2){
//        @RequestParam("task_id")List<Integer> task_id,
//        @RequestParam("place") String place,
//        @RequestParam("school_id") int school_id
        User user = userHelper.getCurrentUser();
        int school_id = user.getSchool_id();
        List<String>a =materialService.get_places(toTask2.getTask_id());
        if(a!=null){
            materialService.delete_task_place(toTask2.getTask_id());
        }
        for (String the_place : toTask2.getThe_place()) {
            materialService.add_task_place(toTask2.getTask_id(),the_place,school_id);
        }
        //存入to_task数据表中一对多
        ResponseResult result = new ResponseResult(200, "任务分配成功");
        return  result;
    }



    //获取当前学校设置的各个任务点


    @GetMapping("get_task_place")
    public ResponseResult get_task_place(String the_place){

        if(the_place=="0"){
            the_place="全部";
        }
        User user = userHelper.getCurrentUser();
        int school_id = user.getSchool_id();
       List<task_place> a = materialService.get_task_place(the_place, school_id);
        ResponseResult result = new ResponseResult(200, "任务地点获取成功",a);

        return  result;
    }

    //获取当前学校的所有任务,分条件查询,分页查询？
    @GetMapping("get_task")
    public ResponseResult get_task(@RequestParam(name = "page_num", defaultValue = "1")Integer page_num,
                                   @RequestParam(name = "page_size", defaultValue = "5")Integer page_size,
                                  int task_type_id,int type){
        User user = userHelper.getCurrentUser();
        int school_id = user.getSchool_id();
        PageInfo<task> tasks = materialService.get_task(page_num,page_size,school_id, task_type_id);


        if (tasks!=null){
            for (int i = 0; i <tasks.getList().size() ; i++) {
                List<String> tasks2 = materialService.get_places(tasks.getList().get(i).getId());
                tasks.getList().get(i).setThe_places(tasks2);
            }
            if(type==1){
                Collections.reverse(tasks.getList());
            }

        }
//        if (tasks!=null){
//            int id = tasks.getList().get(0).getId();
//            for (int i = 1; i <tasks.getList().size() ; i++) {
//                if(tasks.getList().get(i).getId()==id){
//                    tasks.getList().remove(i);
//                    tasks.getList().get(id).
//                }
//            }
//        }

        ResponseResult result = new ResponseResult(200, "任务获取成功", tasks);

        return  result;
    }

    @DeleteMapping("delete_task")
    public ResponseResult delete_task(@RequestParam("id") int id){
        materialService.delete_task(id);
        ResponseResult result = new ResponseResult(200, "任务删除成功");
        return result;
    }


    //获取具体物品
    @GetMapping("get_article")
    public ResponseResult get_article(){

        List<article> articles = materialService.get_article();

        ResponseResult result = new ResponseResult(200, "具体物品获取成功", articles);

        return  result;
    }

    //添加任务
    @PostMapping("add_a_task")
    public ResponseResult add_a_task(@RequestBody task task) throws IOException {

//        String url = null;
//        if(task.getFile()!=null){
//            url = material_Util.uploadImage(task.getFile());
//            task.setImg_url(url);
//        }

//        System.out.println(task);
        User user = userHelper.getCurrentUser();
        int school_id = user.getSchool_id();
        task.setSchool_id(school_id);
        //task.setImg_url(url);
        materialService.add_a_task(task);
        String msg = "新任务";
        SseEmitterServer sseEmitterServer = new SseEmitterServer();
        sseEmitterServer.sendAllClientMsg(msg);

        ResponseResult result = new ResponseResult(200, "任务添加成功",task.getImg_url());
        return result;

    }

    @PostMapping("update_task")
    public ResponseResult update_task(@RequestBody task task) throws IOException {

//        String url = null;
//        if(task.getFile()!=null){
//            url = material_Util.uploadImage(task.getFile());
//        }

//        System.out.println(task);
        User user = userHelper.getCurrentUser();
        int school_id = user.getSchool_id();
        task.setSchool_id(school_id);
//        if(url != null){
//            task.setImg_url(url);
//        }else {
//            url = task.getImg_url();
//        }
        materialService.update_task(task);
        //materialService.update_task(task);

        ResponseResult result = new ResponseResult(200, "任务修改成功");
        return result;

    }

    //获取当前所有的任务类型

    //有问题，这里一定要用public才能正常运行
    @GetMapping("get_task_type")
    public ResponseResult get_task_type(){
        System.out.println("get_task_type");
        List<task_type> types = null;
        int i = 1;
         types = materialService.get_task_type1(i);
        ResponseResult result = null;
        if (types != null) {
            // 继续处理types
             result = new ResponseResult(200, "任务类型获取成功", types);
        } else {
            // 处理获取任务类型失败的情况，例如返回错误信息的ResponseResult
            result = new ResponseResult(200, "任务类型获取失败");
        }

        return result;
    }


    //获取具体物品




}
